//index.js
//获取应用实例
const app = getApp()
const APP_ID = 'wx582499400d94f8bb'; //输入小程序appid  
const APP_SECRET = '52f712132f9b6eae7937491516e29736'; //输入小程序app_secret  
var OPEN_ID = '' //储存获取到openid  
var SESSION_KEY = '' //储存获取到session_key  
Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        //统计数据
        dangerStatics: {
            aLevel: 1,
            bLevel: 2,
            cLevel: 3
        },
        dangerTaskCountInfo: {
            reform: 0, //待整改
            checkAccept: 0, //待验收
            unCheckCount: 0, //带检查
            reformSheet: 0 //发布整改单
        },
    },
    //事件处理函数
    bindViewTap: function () {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    onLoad: function () {
      var userInfo = { username: '顾乾斌', companyName: '宁波市交通建设工程试验检测中心有限公司', headPath:'../../image/person_icon.png'}
        this.setData({
            userInfo: userInfo
        })
        //显示加载中
        wx.showLoading()
        this.getAppInitInfo()
        if (app.globalData.user) {
            this.setData({
                userInfo: app.globalData.user,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
        //获取隐患排查任务的数据
        this.loadDangerTaskInfo();
        //获取隐患统计数据
        this.getDangerStatic();
    },
    getUserInfo: function (e) {
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    getAppInitInfo() {
        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)
        var that = this;
        // 登录
        wx.login({
            success: res => {
                var that1 = that
              wx.request({
                url: app.globalData.baseUrl + '/safe/user/checkWxUserExist',
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: {
                  code: res.code
                },
                method: 'POST',
                success: res => {
                  //console.log(res)
                  if (!res.data.success) {
                    //关闭加载
                    wx.hideLoading()
                    wx.navigateTo({
                      url: '/pages/danger/login/login',
                    })
                  } else {
                    if (res && res.header && res.header['Set-Cookie']) {
                      wx.setStorageSync('sessionid', res.header['Set-Cookie']); //保存Cookie到Storage
                    }
                    app.globalData.user = res.data.data
                    SESSION_KEY=res.data.data.session_key
                    that1.setData({
                      userInfo: res.data.data
                    })

                  }
                }

              })
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                // wx.request({
                //     url: 'https://api.weixin.qq.com/sns/jscode2session',
                //     data: {
                //         appid: APP_ID,
                //         secret: APP_SECRET,
                //         js_code: res.code,
                //         grant_type: 'authorization_code'
                //     },
                //     method: 'GET',
                //     success: function (res) {
                //         console.log(res.data)
                //         OPEN_ID = res.data.openid;
                //         SESSION_KEY = res.data.session_key;
                //         console.log(OPEN_ID.length)
                //         console.log(SESSION_KEY.length)
                //         app.globalData.openid = res.data.openid
                //         app.globalData.session_key = res.data.session_key
                     
                //     }
                // })

            }
        })
        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            app.globalData.userInfo = res.userInfo

                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }
                        }
                    })
                }
            }
        })
    },

    //获取隐患统计数据
    getDangerStatic() {
        var currentDate = new Date();
        var that = this
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        wx.request({
            url: app.globalData.baseUrl + '/safe/index/analysisHiddenDangers/' + currentDate.getFullYear(),
            header: header,
            method: "GET",
            success(res) {
                if (res.data.data.dangerLevel) {
                    let tempObj = res.data.data;
                    that.setData({
                        'dangerStatics': {
                            'aLevel': tempObj.dangerLevel['重大(A级)'],
                            'bLevel': tempObj.dangerLevel['一般(B级)'],
                            'cLevel': tempObj.dangerLevel['一般(C级)']
                        }
                    })
                }
                //关闭加载
                wx.hideLoading()
            },
            fail() {
                //关闭加载
                wx.hideLoading()
            }
        })

    },
    /**
     * 加载隐患的任务数量
     */
    loadDangerTaskInfo() {
        var that = this
        var header;
        wx.showLoading({
            title: '',
        })
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/wechat/dangerTaskTypeCount',
            method: "GET",
            success(res) {
                wx.hideLoading()
                if (res.data.success) {
                    that.setData({
                        dangerTaskCountInfo: res.data.data
                    })
                }
            }
        })
    },
//跳转页面
    emerExamineClick(){
        wx.navigateTo({
            url: '../emergency/emerExamine/emerExamine'
        })
    },
    emgResponseEnter(){
        wx.navigateTo({
            url: '../emergency/emgResponse/emgResponse'
        })
    },
    //查看隐患详情
    viewDangerDetail:function (e) {
        wx.navigateTo({
            url: '../dangerDetailPage/dangerDetailPage?title='+e.currentTarget.dataset.typeName
        })
    }

})
